from typing import List
from .model import UserPartner
from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()


# 设置过滤字段
class Filters(FuFilters):
        
    price_list: bool = Field(None, alias='price_list')    
    credit_point: str = Field(None, alias='credit_point')    
    is_payonline: bool = Field(None, alias='is_payonline')    
    partner_id: str = Field(None, alias='partner_id')    
    user_id: str = Field(None, alias='user_id')


# 设置请求接收字段
class UserPartnerSchemaIn(ModelSchema):

    class Config:
        model = UserPartner
        model_exclude = ['creation_on', 'change_on',  'change_by', 'creation_by', 'partner_id']


# 设置响应字段
class UserPartnerSchemaOut(ModelSchema):

    class Config:
        model = UserPartner
        model_fields = '__all__'


# 创建UserPartner
@router.post('/user_partner', response=UserPartnerSchemaOut)
def create_user_partner(request, data: UserPartnerSchemaIn):
    user_partner = create(request, data, UserPartner)
    return user_partner


# 删除UserPartner
@router.delete('/user_partner/{id}')
def delete_user_partner(request, id: int):
    delete(id, UserPartner)
    return {'success': True}


# 更新UserPartner
@router.put('/user_partner/{id}', response=UserPartnerSchemaOut)
def update_user_partner(request, id: int, data: UserPartnerSchemaIn):
    user_partner = update(request, id, data, UserPartner)
    return user_partner


# 获取UserPartner
@router.get('/user_partner', response=List[UserPartnerSchemaOut])
@paginate(MyPagination)
def list_user_partner(request, filters: Filters = Query(...)):
    qs = retrieve(request, UserPartner, filters)
    return qs


# 导入
@router.get('/user_partner/all/export')
def export_user_partner(request):
    export_fields = ('price_list', 'credit_point', 'is_payonline', 'partner_id', 'user_id', )
    return export_data(request, UserPartner, UserPartnerSchemaOut, export_fields)


# 导出
@router.post('/user_partner/all/import')
def import_user_partner(request, data: ImportSchema):
    import_fields = ('price_list', 'credit_point', 'is_payonline', 'partner_id', 'user_id', )
    return import_data(request, UserPartner, UserPartnerSchemaIn, data, import_fields)
    